﻿Imports System.IO
Imports System.Collections.Specialized
Imports System.Net
Imports System.Threading
Imports System.Xml
Imports System.Text
Imports System.Web

Public Class UploadItem
#Region "Properties"
#Region "Custom Items"
    Enum ProgressState
        Initiated
        Uploading
        Stopped
        Done
        Idle
    End Enum
#End Region
    Private Username As String = "Pathogenix"
    Private _Autostart As Boolean
    Public Property Autostart() As Boolean
        Get
            Return _Autostart
        End Get
        Set(value As Boolean)
            _Autostart = value
        End Set
    End Property
    Private _AutoCopy As Boolean
    Public Property AutoCopy() As Boolean
        Get
            Return _AutoCopy
        End Get
        Set(value As Boolean)
            _AutoCopy = value
        End Set
    End Property
    Private _ShowProgress As Boolean
    Public Property ShowProgress() As Boolean
        Get
            Return _ShowProgress
        End Get
        Set(value As Boolean)
            _ShowProgress = value
        End Set
    End Property
    Private _ItemID As Integer = -1
    Public Property ItemID() As Integer
        Get
            Return _ItemID
        End Get
        Set(value As Integer)
            _ItemID = value
        End Set
    End Property
    Private _ItemFilename As String = Nothing
    Public Property ItemFilename() As String
        Get
            Return _ItemFilename
        End Get
        Set(value As String)
            _ItemFilename = value
        End Set
    End Property
    Private _ImageURL As String = Nothing
    Public Property ImageURL() As String
        Get
            Return _ImageURL
        End Get
        Set(value As String)
            _ImageURL = value
        End Set
    End Property
    Private _UploadState As ProgressState = ProgressState.Idle
    Public ReadOnly Property UploadState() As ProgressState
        Get
            Return _UploadState
        End Get
    End Property
    Private _Progress As Integer = 0
    Public ReadOnly Property Progress() As Integer
        Get
            Return _Progress
        End Get
    End Property
#End Region
#Region "Events"
    Delegate Sub EventDelegate(sender As UploadItem)
    Delegate Sub StateDelegate(sender As UploadItem)
    Public Event OnStateChanged As StateDelegate
    Public Const ApiKey As String = "da07c61a0b01f258fdffc72a15a721ec"
    Private Const MaxHeight As Integer = 70
    Private MeDisposed As Boolean = True
    Protected Overrides Sub OnSizeChanged(e As EventArgs)
        Me.MinimumSize = New Point(500, 70)
        Me.MaximumSize = New Point(10000, 70)
        MyBase.OnSizeChanged(e)
    End Sub
    Private Sub ChangeState(ByVal State As ProgressState)
        If State <> UploadState Then
            _UploadState = State
            RaiseEvent OnStateChanged(Me)
        End If
    End Sub
#End Region
#Region "Uploader"
    Public Event OnFinish()
    Private WithEvents WebClient As New WebClient
    Public Sub StartUpload()
        If CmdStart.Text = "Start Upload" Then
            If ShowProgress = True Then FrmProgress.Show()
            CmdStart.Enabled = False

            Dim imageData() As Byte
            Dim fileStream As FileStream = System.IO.File.OpenRead(ItemFilename)
            imageData = New Byte((fileStream.Length) - 1) {}
            fileStream.Read(imageData, 0, imageData.Length)
            fileStream.Close()

            Dim Values = New NameValueCollection()
            Values.Add("key", ApiKey)
            Values.Add("image", Convert.ToBase64String(imageData))

            WebClient.UploadValuesAsync(New Uri("http://api.imgur.com/2/upload.xml"), "POST", Values)

            imageData = Nothing
            fileStream.Dispose()
            ChangeState(ProgressState.Initiated)
            CmdStart.Text = "Queued"
        End If
    End Sub
    Private Sub WebClient_UploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs) Handles WebClient.UploadProgressChanged
        _Progress = e.ProgressPercentage * 2
        If ShowProgress = True Then FrmProgress.SetProgress(Progress)
        If Progress <= 100 And Progress >= 0 Then
            If e.ProgressPercentage = 50 Then
                Progressbar1.Text = "Requesting URL from Server..."
            Else
                Progressbar1.Value = Progress
            End If
            Progressbar1.Text = Progress & "% (" & Math.Round(e.BytesSent / 1024 / 1024, 2) & "/" & Math.Round(e.TotalBytesToSend / 1024 / 1024, 2) & "MB)"
            CmdStart.Text = "Uploading..."
        End If
        ChangeState(ProgressState.Uploading)
    End Sub
    Private Sub WebClient_UploadValuesCompleted(sender As Object, e As UploadValuesCompletedEventArgs) Handles WebClient.UploadValuesCompleted
        Try
            Dim enc As New System.Text.UTF8Encoding()
            Dim Str As String = enc.GetString(e.Result)
            ImageURL = Split(Str, "<original>")(1).Split("<")(0)
            If AutoCopy = True Then My.Computer.Clipboard.SetText(ImageURL)
            CmdStart.Enabled = True
            CmdStart.Text = "Copy URL"
            _Progress = 100
            Progressbar1.Value = 100
            Progressbar1.Text = "Finished Uploading"
            RaiseEvent OnFinish()
        Catch ex As Exception
            CmdStart.Enabled = True
            CmdStart.Text = "Start Upload"
            Progressbar1.Text = "Failed to Upload."
            StartUpload()
        End Try
        FrmProgress.Close()
    End Sub
#End Region
    Public Sub New(ByVal Settings As UploadSettings)

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ItemID = Settings.ID
        ItemFilename = Settings.Filename
        Autostart = Settings.AutoStart
        AutoCopy = Settings.AutoCopy
        ShowProgress = Settings.ShowProgress
        PicThumb.BackgroundImageLayout = ImageLayout.Zoom
        Me.MinimumSize = New Point(500, 70)
        Me.MaximumSize = New Point(10000, 70)
        Try
            PicThumb.BackgroundImage = New Bitmap(ItemFilename)
        Catch ex As Exception
        End Try
        LblFilename.Text = Path.GetFileName(ItemFilename)
        Me.Dock = DockStyle.Top
    End Sub
    Private Sub OnStart(sender As Object, e As EventArgs) Handles MyBase.Load
        MeDisposed = False
        If Autostart = True Then StartUpload()
        Me.Dock = DockStyle.Top
    End Sub
    Private Sub CmdClose_Click(sender As Object, e As EventArgs) Handles CmdClose.Click
        Try
            Dim contrl As Control = Me.GetNextControl(Me, True)
            Do Until contrl Is Nothing
                Try
                    contrl = Me.GetNextControl(contrl, True)
                    Dim ctrl As Control = DirectCast(contrl, Control)
                    ctrl.Dispose()
                Catch ex As Exception
                End Try
            Loop
        Catch ex As Exception
        End Try
        MeDisposed = True
        Me.Dispose()
    End Sub
    Private Sub StartUpload_Click(sender As Object, e As EventArgs) Handles CmdStart.Click
        If CmdStart.Text = "Start Upload" Then
            StartUpload()
        ElseIf CmdStart.Text = "Copy URL" Then
            My.Computer.Clipboard.SetText(ImageURL)
            CmdStart.Text = "Copied!"
        End If
    End Sub
    Private Sub CmdStart_MouseLeave(sender As Object, e As EventArgs) Handles CmdStart.MouseLeave
        If CmdStart.Text = "Copied!" Then CmdStart.Text = "Copy URL"
    End Sub
    Private Sub PicThumb_MouseHover(sender As Object, e As EventArgs) Handles PicThumb.MouseHover
        Dim Preview As New ImagePreivew(Me.ItemFilename)
    End Sub
End Class

